package com.eric.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class ServerThread implements Runnable {
	// 当前要处理的Socket对象
	Socket s = null;
	// 读取客户端的数据
	BufferedReader br;

	public ServerThread(Socket s) {
		this.s = s;
		if (null != s) {
			try {
				br = new BufferedReader(new InputStreamReader(s.getInputStream(),"utf-8"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void run() {
		String content = null;
		// TODO Auto-generated method stub
        while((content = readFromClient()) != null) {
        	   for(Socket s : MutiThreadServerSocket.socketList) {
        		   try {
					OutputStream os = s.getOutputStream();
					os.write(content.getBytes("uft-8"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	   }
        }
		
	}
	
	
	/**
	 * 读取客户端数据
	 * @return
	 */
	public String readFromClient () {
		if(null != br) {
			try {
				return br.readLine();
			} catch (IOException e) {
				//捕捉到异常，表明s 对应的客户端已经关闭
				MutiThreadServerSocket.socketList.remove(s);
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

}
